<template>
    <div>
        <el-button @click="handleVisible(true)">选择优惠券</el-button>
        <span style="color: #ff6b00; margin-left: 8px">{{ couponName }}</span>
    </div>
    <el-dialog class="coupon-custom-dialog" v-model="visible" title="选择优惠券">
        <el-form ref="formRef" :model="form" label-width="auto">
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="优惠券名称" prop="couponName">
                        <el-input v-model="form.couponName" clearable placeholder="请输入优惠券名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="优惠券状态" prop="couponStatus">
                        <el-select v-model="form.couponStatus" clearable placeholder="请选择状态">
                            <el-option
                                v-for="item in couponStatusListCopy"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" class="zw-form-btns">
                    <el-button type="primary" @click="searchHandler">查询</el-button>
                    <el-button plain @click="resetHandler">清空</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableList">
            <el-table-column v-for="{ prop, slot, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                <template v-if="slot" #default="{ row }">
                    <el-button
                        size="small"
                        v-if="prop === 'operation'"
                        @click="handleSelect(row)"
                        :disabled="row.id === modelValue">
                        {{ row.id === modelValue ? '已选择' : '选择' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :total="totalCount"
            :page-size="form.perPage"
            :current-page="form.page"
            @sizeChange="changeSizeHandler"
            @pageChange="changePageHandler" />
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, floatDivide } from '@/commons/utils';
import Pagination from '@/components/Pagination.vue';

const couponTypeList = reactive(packSelectObjUtil(constants.COUPON_TYPE_OPTIONS));
const couponStatusList = reactive(packSelectObjUtil(constants.COUPON_STATUS_OPTIONS));
const couponStatusListCopy = [couponStatusList[0], couponStatusList[1]];

const props = defineProps(['modelValue']);

const emit = defineEmits(['update:modelValue', 'handle-change']);

let form = reactive({
    page: 1,
    perPage: 10,
    couponName: null,
    couponStatus: null,
    couponType: null,
    couponSubStatus: 1
});
const formRef = ref();
let tableList = reactive([]);
let totalCount = ref(0);

let visible = ref(false);
const tableColumns = reactive([
    { label: '优惠券名称', prop: 'couponName', showOverflowTooltip: true },
    { label: '优惠内容', prop: 'content' },
    { label: '剩余库存', prop: 'restNumber' },
    { label: '状态', prop: 'couponStatusName' },
    { label: '操作', prop: 'operation', slot: true }
]);

let couponName = ref(null);
watch(
    () => props.modelValue,
    async val => {
        if (!val) {
            return;
        }
        const { data } = await request('couponDetailServ', { id: val });
        couponName.value = data.couponName;
    }
);

const handleVisible = (isVisible = false) => {
    visible.value = isVisible;
};

const handleSelect = row => {
    emit('handle-change', row);
    emit('update:modelValue', row.id);
    handleVisible(false);
};

const couponContent = obj => {
    const { couponPrerequisites, couponType, couponPrerequisitesAdditional, couponDiscountContent } = obj;
    const pre = [
        '无门槛',
        `满${floatDivide(couponPrerequisitesAdditional, 100)}`,
        `满${couponPrerequisitesAdditional}件`
    ];
    const num = [`减${floatDivide(couponDiscountContent, 100)}`, `打${floatDivide(couponDiscountContent, 100)}折`];
    return (pre[couponPrerequisites - 1] || '') + (num[couponType - 1] || '');
};

/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('couponListServ', form);
    const list = (res.data.list || []).map(({ id, couponAcquiredNumber, couponInfo }) => {
        const item = {
            ...couponInfo?.[0]
        };
        item.restNumber = item.couponTotal - couponAcquiredNumber;
        item.content = couponContent(item);
        item.id = id;
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    queryCouponListHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};

queryCouponListHandler();

defineExpose({
    handleVisible
});
</script>

<style lang="scss">
.coupon-custom-dialog {
    max-width: 800px;
    min-width: 800px;
}
</style>
<style lang="scss" scoped></style>
